import cv2  
import time  
  
# cap = cv2.VideoCapture(9)  
cap = cv2.VideoCapture(9, cv2.CAP_V4L)
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))  
  
while True:  
    ret, frame = cap.read()  
    if not ret:
        time.sleep(1)
        cap = cv2.VideoCapture(9, cv2.CAP_V4L)
        cap.set(cv2.CAP_PROP_FOURCC,cv2.VideoWriter_fourcc('M','J','P','G'))  
        print("无法从摄像头读取帧 (Stream end?). Exiting ...")  
        break  
  
    cv2.imshow('frame', frame)  
  
    # 按下'q'键退出循环  
    if cv2.waitKey(1) & 0xFF == ord('q'):  
        break  
  
# 释放摄像头资源  
cap.release()  
# 关闭所有OpenCV窗口  
cv2.destroyAllWindows()